package com.xf.zk.curator.example.elections;

import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.recipes.leader.LeaderSelector;
import org.apache.curator.framework.recipes.leader.LeaderSelectorListenerAdapter;
import org.apache.curator.retry.ExponentialBackoffRetry;

public class LeaderSelectorTest {
    static String leader_path = "/curator_recipes_leader_path";

    public static void main(String[] args) throws Exception {
        // 模拟3个线程分别获取1个客户端连接进行master选举
        Runnable target = new Runnable() {
            @Override
            public void run() {
                CuratorFramework client = newClient();
                client.start();
                // 新建LeaderSelector,路径为/curator_recipes_leader_path，并注册
                LeaderSelector selector = new LeaderSelector(client, leader_path, new LeaderSelectorListenerAdapter() {
                    // 选举为master成功回调
                    public void takeLeadership(CuratorFramework client) throws Exception {
                        System.out.println(Thread.currentThread().getName() + "成为Master角色");
                        // 此处执行选举成功后的业务逻辑
                        Thread.sleep(3000);
                        System.out.println(Thread.currentThread().getName() + "完成Master操作，释放Master权利");
                    }
                });
                // 该方法能让客户端在释放leader权限后 重新加入leader权限的争夺中
                selector.autoRequeue();
                // 开始争夺
                selector.start();
            }
        };
		Thread thread1 = new Thread(target);
		Thread thread2 = new Thread(target);
		Thread thread3 = new Thread(target);
		thread1.start();
		thread2.start();
		thread3.start();
        Thread.sleep(Integer.MAX_VALUE);
    }

    public static CuratorFramework newClient() {
        return CuratorFrameworkFactory.builder().connectString("127.0.0.1:2181,127.0.0.1:2182,127.0.0.1:2183")
				.retryPolicy(new ExponentialBackoffRetry(1000, 3)).build();
    }

}
